/**
 * Project SearchEngine
 */

/**
 * DirScanner implementation
 */

#include "DirScanner.h"

#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#include <iostream>
using std::cout;
using std::endl;

DirScanner::DirScanner()
/* : _dirname(dirname) */
{
    /* cout << "DirScanner" << endl; */
}
DirScanner::~DirScanner()
{

}

void DirScanner::operator()(const string& dirname)
{
    traverse(dirname);
    /* vector<string>::iterator it; */
    /* for (it = _files.begin(); it != _files.end(); ++it) { */
    /*     cout << *it << endl; */
    /* } */
}
vector<string>& DirScanner::getFiles() {
    return _files;
}

void DirScanner::traverse(const string& dirname) {
    char pathc[1<<9] = {0};
    strcpy(pathc, dirname.c_str());
    char file_path[1<<9] = {0};
    char file[1<<9] = {0};
    DIR* dir = opendir(pathc);
    if (NULL == dir) {
        perror("opendir failed!");
        return;
    }
    struct dirent* ptr = nullptr;
    struct stat buf;
    int i, j;

    while ((ptr = readdir(dir)) != NULL) {
        if (ptr->d_name[0] != '.') {
            //除去根目录
            strcpy(file_path, pathc);
            if (pathc[strlen(pathc) - 1] != '/')
                strcat(file_path, "/");
            strcat(file_path, ptr->d_name);
            assert(stat(file_path, &buf) != -1);
            if (S_ISREG(buf.st_mode)) {
                //判断是文件
                for (i = 0; i < (int)strlen(file_path); i++) {
                    if ('/' == file_path[i]) {
                        memset(file, 0, strlen(file));
                        j = 0;
                        continue;
                    }
                    file[j++] = file_path[i];
                }
                _files.push_back(file_path);
            }
            else if (S_ISDIR(buf.st_mode)) {
                //判断是目录
                traverse(file_path);
            }
        }

    }

}
